package com.vf.admin.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.utils.httpqingqiu.HttpPostUtils;
import okhttp3.*;
import org.apache.commons.lang.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取token类
 */
public class BaiDuAuthUtil {
    private static String CLIENT_ID = "6VDiUPHp4QbFmBGzscAsG7i4";
    private static String CLIENT_SECRET = "4WrfNF659RGwben3ysWR0nv8Nc87eI3r";
//    private static String CLIENT_ID = "gGmg3Unf9oC7h1r8XOfwT2Fy";
//    private static String CLIENT_SECRET = "t68zdk11oUoe6RgmFtmXggxxxIHveQwN";

    private static final String SEARCH_URL = "https://aip.baidubce.com/rest/2.0/face/v3/search?access_token=";

    private static final String DETECT_URL = "https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=";
    private static final String VERIFY_URL = "https://aip.baidubce.com/rest/2.0/face/v4/mingjing/verify?access_token=";

    private static final String ADD_URL = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add?access_token=";
    private static final String MATCH_URL = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=";
    private static final String GET_USER_URL = "http://106.13.91.231:8300/face-api/v3/face/list?appid=";
    private static final String UPDATE_URL = "http://106.13.91.231:8300/face-api/v3/face/update?appid=";
    private static final String DEL_URL = "http://106.13.91.231:8300/face-api/v3/face/delete?appid=";

    public static final Integer VERIFY_STATUS = 0;

    public static String getAccessToken(RedisUtil redisUtil) {
        String accessToken = null;
        Object o = redisUtil.get(RedisKeys.BAIDU_ACCESS_TOKEN);
        if (o != null) {
            accessToken = redisUtil.get(RedisKeys.BAIDU_ACCESS_TOKEN).toString();
        }
        if (StringUtils.isEmpty(accessToken)) {
            JSONObject jsonObject = getAuth();
            accessToken = jsonObject.getString("access_token");
            redisUtil.set(RedisKeys.BAIDU_ACCESS_TOKEN, accessToken, jsonObject.getIntValue("expires_in"));
        }
        return accessToken;
    }


//    public static JSONObject getAuth() {
//
//        OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
//
//        MediaType mediaType = MediaType.parse("application/json");
//        RequestBody body = RequestBody.create(mediaType, "");
//        Request request = new Request.Builder()
//                .url("https://aip.baidubce.com/oauth/2.0/token?client_id=6VDiUPHp4QbFmBGzscAsG7i4&client_secret=4WrfNF659RGwben3ysWR0nv8Nc87eI3r&grant_type=client_credentials")
//                .method("POST", body)
//                .addHeader("Content-Type", "application/json")
//                .addHeader("Accept", "application/json")
//                .build();
//        Response response = null;
//        try {
//            response = HTTP_CLIENT.newCall(request).execute();
//            System.out.println("hdhdh" + response.body().string());
//
//
//            return JSONObject.parseObject()
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
//
//    }


    public static JSONObject getAuth() {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost

                // 2. 官网获取的 API Key
                + "&client_id=" + CLIENT_ID
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + CLIENT_SECRET
                // 1. grant_type为固定参数
                + "&grant_type=client_credentials";

        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
//            Map<String, List<String>> map = connection.getHeaderFields();
//            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                System.err.println(key + "--->" + map.get(key));
//            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */

            System.err.println("result:" + result);
            return JSONObject.parseObject(result);
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

    /**
     * 人脸搜索
     *
     * @param imgBase64
     * @param imageType
     * @return
     */
    public static JSONObject searchFace(String imgBase64, String imageType) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("image", imgBase64);
        map.put("image_type", imageType);
        map.put("group_id_list", "group1");
        map.put("match_threshold", 80);
        return JSONObject.parseObject(HttpPostUtils.getInstance().sendPostBody(SEARCH_URL, "", JSON.toJSONString(map)));
    }

    /**
     * 人脸检测
     *
     * @param imgBase64
     * @return
     */
    public static JSONObject detect(String imgBase64) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("image", imgBase64);
        map.put("image_type", "URL");
        map.put("face_field", "gender");
        return JSONObject.parseObject(HttpPostUtils.getInstance().sendPostBody(DETECT_URL, "", JSON.toJSONString(map)));
    }

    /**
     * 人脸搜索
     *
     * @param imgBase64
     * @param imageType
     * @param groupIdList
     * @return
     */
    public static JSONObject searchFace(String uid, String imgBase64, String imageType, String groupIdList, int match_threshold) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("image", imgBase64);
        map.put("image_type", imageType);
        map.put("group_id_list", groupIdList);
        map.put("user_id", uid);
        map.put("match_threshold", match_threshold);
        return JSONObject.parseObject(HttpPostUtils.getInstance().sendPostBody(SEARCH_URL, "", JSON.toJSONString(map)));
    }

    /**
     * 人脸注册
     *
     * @param imgBase64
     * @param imageType
     * @param userId
     * @return
     */
    public static JSONObject addFace(String imgBase64, String imageType, String userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("image", imgBase64);
        map.put("image_type", imageType);
        map.put("group_id", "group1");
        map.put("user_id", userId);
        map.put("quality_control", "NORMAL");
        return JSONObject.parseObject(HttpPostUtils.getInstance().sendPostBody(ADD_URL, "", JSON.toJSONString(map)));
    }

    public static JSONObject match(RedisUtil redisUtil, String imgUrl1, String imgUrl2) {
        JSONObject imgJson1 = new JSONObject();
        imgJson1.put("image", imgUrl1);
        imgJson1.put("image_type", "URL");

        JSONObject imgJson2 = new JSONObject();
        imgJson2.put("image", imgUrl2);
        imgJson2.put("image_type", "URL");
        JSONArray jsonArray = new JSONArray(Arrays.asList(imgJson1, imgJson2));

        String result = HttpPostUtils.getInstance().sendPostBody(MATCH_URL + getAccessToken(redisUtil), "", jsonArray.toJSONString());
        return JSONObject.parseObject(result);
    }

    /**
     * 人脸注册
     *
     * @param groupId
     * @param userId
     * @return
     */
    public static JSONObject updateFace(String imgBase64, String imageType, String groupId, String userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("image", imgBase64);
        map.put("image_type", imageType);
        map.put("group_id", groupId);
        map.put("user_id", userId);
        map.put("quality_control", "NORMAL");
        return JSONObject.parseObject(HttpPostUtils.getInstance().sendPostBody(UPDATE_URL, "", JSON.toJSONString(map)));
    }


    /**
     * 人脸注册
     *
     * @param groupId
     * @param userId
     * @return
     */
    public static JSONObject delFace(String groupId, String userId, String face_token) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("group_id", groupId);
        map.put("user_id", userId);
        map.put("face_token", face_token);
        return JSONObject.parseObject(HttpPostUtils.getInstance().sendPostBody(DEL_URL, "", JSON.toJSONString(map)));
    }

    /**
     * 获取
     *
     * @param groupId
     * @param userId
     * @return
     */
    public static JSONObject getFace(String groupId, String userId) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("group_id", groupId);
        map.put("user_id", userId);
        return JSONObject.parseObject(HttpPostUtils.getInstance().sendPostBody(GET_USER_URL, "", JSON.toJSONString(map)));
    }

    public static JSONObject verify(RedisUtil redisUtil, String name, String idNum, String image) {
        try {
            HashMap<String, Object> map = new HashMap<>();
            map.put("image", image);
            map.put("image_type", "BASE64");
            map.put("id_card_number", idNum);
            //map.put("name", new String(name.getBytes(), "UTF-8"));
            map.put("name", name);
            return JSONObject.parseObject(HttpPostUtils.getInstance().sendPostBody(VERIFY_URL + getAccessToken(redisUtil), "", JSON.toJSONString(map)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*public static void main(String[] args) {
        try {
            System.out.println(addGroup());
        } catch (Exception e) {
            e.printStackTrace();
        }  //IO异常


    }

    public static JSONObject addGroup() {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/add?access_token=" + getAccessToken();
        HashMap<String, Object> map = new HashMap<>();
        map.put("group_id", "group1");
        return JSONObject.parseObject(HttpPostUtils.getInstance().sendPostBody(url, "", JSON.toJSONString(map)));
    }

    public static JSONObject deleteGroup(String appid) {
        String url = "http://106.13.91.231:8300/face-api/v3/group/delete?appid=" + appid;
        HashMap<String, Object> map = new HashMap<>();
        map.put("group_id", "group1");
        return JSONObject.parseObject(HttpPostUtils.getInstance().sendPostBody(url, "", JSON.toJSONString(map)));
    }

    public static JSONObject getGroup(String appid) {
        String url = "http://106.13.91.231:8300/face-api/v3/group/list?appid=" + appid;
        HashMap<String, Object> map = new HashMap<>();
//        map.put("group_id","group1");
        return JSONObject.parseObject(HttpPostUtils.getInstance().sendPostBody(url, "", JSON.toJSONString(map)));
    }*/


}
